//实体管理功能接口
import { useAxios } from '@/hooks/web/useAxios'
import { useCache } from '@/hooks/web/useCache'
const request = useAxios()
const { wsCache } = useCache()
const Cache_Entity = 'ezlcp-Select-Entity'

/**
 * @description  查询实体（不包括当前实体ID）
 */
export const selectEntity = async () => {
  let data = wsCache.get(Cache_Entity)
  if (!data) {
    data = (await selectEntityApi(null)).data as any
    wsCache.set(Cache_Entity, data, { exp: 60 * 5 }) //5分钟
  }
  return data
}

/**
 * @description  查询实体（不包括当前实体ID）
 */
const selectEntityApi = (entId) => {
  return request.postXww({
    url: 'form/entity/selectEntity',
    params: { entId: entId }
  })
}

//查询某模块下的实体
export const selectEntityByModId = (moduleId) => {
  return request.postXww({
    url: 'form/entity/selectByModuleId',
    params: { moduleId: moduleId }
  })
}

//获取实体默认字段
export const getFixedCols = async (): Promise<any> => {
  const key = 'ezlcp-FixedCols'
  let data = wsCache.get(key)
  if (!data) {
    data = (await getFixedColsApi()).data as any
    wsCache.set(key, data, { exp: 86400 }) //24小时
  }
  return data
}
/**
 * 获取自定义实体固定字段
 */
const getFixedColsApi = () => {
  return request.post({
    url: 'form/entity/getFixedCols'
  })
}

//获取实体数据类型
export const getDataTypes = async (): Promise<any> => {
  const key = 'ezlcp-DataTypes'
  let data = wsCache.get(key)
  if (!data) {
    data = (await getDataTypesM()).data as any
    wsCache.set(key, data)
  }
  return data
}

/**
 * 获取实体数据类型
 */
const getDataTypesM = () => {
  return request.post({
    url: 'form/entity/getDataTypes'
  })
}

/**
 * 查询实体
 */
export const queryEntity = (data) => {
  return request.post({
    url: 'form/entity/query',
    data
  })
}

/**
 * @description  查询单个实体
 */
export const getEntity = (id) => {
  return request.postXww({
    url: 'form/entity/get',
    params: { pkId: id }
  })
}
/**
 * @description  发布实体
 */
export const publishEnt = (entId) => {
  wsCache.delete(Cache_Entity)
  return request.postXww({
    url: 'form/entity/publish',
    params: { entId: entId }
  })
}

/**
 * @description  从数据库中的已存在的表或视图逆向生成实体
 */
export const createFromDB = (data) => {
  return request.postXww({
    url: 'form/entity/createFromDB',
    params: data
  })
}
/**
 * @description  删除实体
 */
export const delEntity = (id) => {
  wsCache.delete(Cache_Entity)
  return request.postXww({
    url: 'form/entity/delete',
    params: { id: id, delTable: true }
  })
}

/**
 * @description  检查物理表名是否重复
 */
export const checkTableName = (tableName, entId, dsId) => {
  return request.postXww({
    url: 'form/entity/checkTableName',
    params: { tableName: tableName, entId: entId, dsId: dsId }
  })
}

/**
 * @description 保存实体
 */
export const saveEntity = (data) => {
  wsCache.delete(Cache_Entity)
  return request.post({
    url: 'form/entity/saveEnt',
    data: data
  })
}
